package longestExp;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;

/**
 * Date:2024/12/10
 * @author Isabella
 * Description: 提取工作经验，但年份取的是区间最大数字 （记得map每次都被调用一次）
 */
public class LongestExpMapper extends Mapper<Object, Text, Text, IntWritable> {

    private final static IntWritable experience = new IntWritable();
    private final static Text jobT = new Text();

    public void map(Object key, Text value, Context context) throws IOException, InterruptedException {
        // 解析数据
        String[] fields = value.toString().split(",");

        // 获取职位名称和工作经验字段
        String jobType = fields[3];
        String experienceReq = fields[8];

        // 将经验转化为整数
        int expYears = getExperienceInYears(experienceReq);

        jobT.set(jobType);
        experience.set(expYears);

        context.write(jobT, experience);
    }

    /**
     * 将经验范围转化为最大年份
     * @param experienceReq 工作经验要求字段
     * @return 最大经验年份
     */
    private int getExperienceInYears(String experienceReq) {
        String extraS = "年";
        String conectS = "-";
        if (experienceReq.contains(extraS)) {
            // 区间，"1-2年"
            if (experienceReq.contains(conectS)) {
                String[] parts = experienceReq.split(conectS);
                return Integer.parseInt(parts[1].replace(extraS, ""));
            } else {
                // 单一年份，"x年"
                return Integer.parseInt(experienceReq.replace(extraS, ""));
            }
        }
        return 0;
    }
}
